package paas.storage.common.config;

import org.apache.commons.lang.StringUtils;
import org.apache.hadoop.hbase.NamespaceDescriptor;
import org.apache.hadoop.hbase.NamespaceExistException;
import org.apache.hadoop.hbase.NamespaceNotFoundException;
import org.apache.hadoop.hbase.TableName;
import org.apache.hadoop.hbase.client.Admin;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import paas.storage.common.utils.AssertUtils;

import java.io.IOException;

/**
 * @Author: Sorin
 * @Descriptions: HBaseDao操作公共类
 * @Date: Created in 2018/3/22
 */
@Component("hBaseDaoUtil")
public class HBaseDaoUtil {
    @Autowired
    ConnectionManager connectionManager;

    private static Logger log = LoggerFactory.getLogger(ConnectionManager.class);


    /**
     * 创建命名空间 (数据库表)
     *
     * @param namespace
     */
    public void createNameSpace(String connectionId, String namespace) throws IOException {

        // 1.创建命名空间描述器
        NamespaceDescriptor namespaceDescriptor = NamespaceDescriptor.create(namespace).build();
        Admin admin = connectionManager.getConnection(connectionId).getAdmin();
        // 2.创建命名空间
        try {
            //不存在抛异常
            NamespaceDescriptor descriptor = admin.getNamespaceDescriptor(namespace);
        } catch (NamespaceExistException e) {
            log.info(namespace + "数据库已存在!");

        } catch (NamespaceNotFoundException e) {
            admin.createNamespace(namespaceDescriptor);
        }
    }

    /**
     * 获取命名空间表
     *
     * @param namespace
     */
    public TableName getTable(String namespace, String table) {
        AssertUtils.isTrue(StringUtils.isEmpty(table), "表不能为空");
        TableName tn = TableName.valueOf("default", table);
        if (namespace != null) {
            tn = TableName.valueOf(namespace, table);
        }
        return tn;
    }

}
